package com.jinliang.thinkinspringweb.mvc.config.interceptor;

import com.jinliang.thinkinspringweb.mvc.config.annotation.RateLimitBucket;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.invoke.MethodHandle;

public class RateLimitBucketInterceptor implements HandlerInterceptor {
    private RedisTemplate redisTemplate;

    public RateLimitBucketInterceptor(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            RateLimitBucket methodAnnotation = handlerMethod.getMethodAnnotation(RateLimitBucket.class);
            if (methodAnnotation == null) {
                return true;
            }
            Long rateLimitBucket = redisTemplate.opsForValue().increment("RateLimitBucket");
            if (rateLimitBucket > 10) {
                throw new Exception("xial liu");
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) throws Exception {
    }
}

